package com.george.shiro.model.controller;

import com.george.shiro.model.entity.Role;
import com.george.shiro.model.service.IRoleResourcesService;
import com.george.shiro.model.service.IRoleService;
import com.george.shiro.model.service.ShiroService;
import com.george.shiro.result.PageResult;
import com.george.shiro.result.ResponseVO;
import com.george.shiro.util.ResultUtil;
import com.george.shiro.vo.RoleConditionVO;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  角色相关
 * </p>
 *
 * @author GeorgeChan 2019/5/26 16:28
 * @version 1.0
 * @since jdk1.8
 */
@RestController
@RequestMapping("/roles")
public class RoleController {
    private final IRoleService roleService;
    private final IRoleResourcesService roleResourcesService;
    private final ShiroService shiroService;

    @Autowired
    public RoleController(IRoleService roleService, IRoleResourcesService roleResourcesService, ShiroService shiroService) {
        this.roleService = roleService;
        this.roleResourcesService = roleResourcesService;
        this.shiroService = shiroService;
    }

    /**
     * 角色列表接口
     * @param vo
     * @return
     */
    @RequiresPermissions("roles")
    @PostMapping("/list")
    public PageResult getAll(RoleConditionVO vo) {
        PageInfo<Role> pageInfo = roleService.findPageBreakByCondition(vo);
        return ResultUtil.tablePage(pageInfo);
    }

    /**
     * 更新角色权限
     * @param roleId
     * @param resourcesId
     * @return
     */
    @RequiresPermissions("role:allotResource")
    @PostMapping("/saveRoleResources")
    public ResponseVO saveRoleResources(Long roleId, String resourcesId) {
        if (StringUtils.isEmpty(roleId)) {
            return ResultUtil.error("error");
        }
        roleResourcesService.addRoleResources(roleId, resourcesId);
        // 重新加载所有拥有roleId的用户的权限信息
        shiroService.reloadAuthorizingByRoleId(roleId);
        return ResultUtil.success("成功");
    }
}
